#include "ChatWidget.h"
#include "ReadFile.h"

#include <QVBoxLayout>
#include <QDateTime>
#include <QFileDialog>
#include <QDebug>

ChatWidget::ChatWidget(QWidget *parent)
    : QWidget{parent}
{
    this->setFixedSize(740,720);
    this->setWindowFlag(Qt::FramelessWindowHint);
    init();
}

void ChatWidget::init()
{
    m_TextEdit = new QTextEdit(this);
    m_TextEdit->resize(740,110);
    m_TextEdit->move(0,570);
    m_SendButton = new QPushButton("发送",this);
    m_SendButton->setObjectName("sendButton");
    m_SendButton->resize(60,35);
    m_SendButton->move(640,680);;
    m_FileButton = new CustomButton(":/iconFile/fileIcon.png",this);
    m_FileButton->resize(20,20);
    m_FileButton->move(5,545);
    m_SettingButton = new CustomButton(":/iconFile/more.png",this);
    m_SettingButton->resize(25,25);
    m_SettingButton->move(690,13);
    m_SettingWidget = new SettingWidget(this);
    m_SettingWidget->move(rect().width()/2 - m_SettingWidget->width()/2,rect().height()/2 - m_SettingWidget->height()/2);

    // ========== 新增聊天视图部分 ==========
    m_chatView = new QListView(this);
    m_chatModel = new ChatMessageModel(this);
    m_delegate = new ChatMessageDelegate(this);

    // 设置视图位置和尺寸
    m_chatView->move(0, 50);            // 位置 (0,50)
    m_chatView->setFixedSize(740, 490); // 固定大小740x450

    // 视图属性设置
    m_chatView->setModel(m_chatModel);
    m_chatView->setItemDelegate(m_delegate);
    m_chatView->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    m_chatView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // 禁用水平滚动
    m_chatView->setStyleSheet("background: #f5f5f5;"); // 设置白色背景

    connect(m_FileButton,&QPushButton::clicked,this,&ChatWidget::getFilePath);
    connect(m_SettingButton,&QPushButton::clicked,this,[=](){
        m_SettingWidget->show();
    });
    connect(m_SettingWidget,&SettingWidget::signal_UpdateFileSavePath,this,&ChatWidget::signal_UpdateFilePath);

    // 自动滚动到底部
    QObject::connect(m_chatModel, &ChatMessageModel::rowsInserted, m_chatView, [=](){
        m_chatView->scrollToBottom();
    });

    connect(m_SendButton,&QPushButton::clicked,this,[=](){
        m_chatModel->updateMessageContent(1,"222");
        if(m_TextEdit->toPlainText().isEmpty()) return;
        QString messageStr = m_TextEdit->toPlainText();
        emit singal_SendMessage(m_ClientIP,messageStr);
        m_TextEdit->clear();
        m_chatModel->addMessage({messageStr,QDateTime::currentMSecsSinceEpoch(),":/iconFile/heardIcon.png",true,0});
    });

    this->setStyleSheet(ReadFile::getIntance()->readQssFile(":/qss/chatWidget.qss"));

    addMessage({
                "data.messageData",
                QDateTime::currentMSecsSinceEpoch(),
                ":/iconFile/heardTest.png",
                false,  // 接收方消息
                0});

    addMessage({
                "data.messageData",
                QDateTime::currentMSecsSinceEpoch(),
                ":/iconFile/heardTest.png",
                true,  // 接收方消息
                0});
}

void ChatWidget::setClientIP(QString clientIP)
{
    m_ClientIP = clientIP;
    update();
}

void ChatWidget::setClientName(QString clientName)
{
    m_ClientName = clientName;
    update();
}

void ChatWidget::addMessage(const ChatMessageModel::ChatMessage &message)
{
    m_chatModel->addMessage(message);
}

void ChatWidget::paintEvent(QPaintEvent *event)
{
    QWidget::paintEvent(event); // 先绘制子控件
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    drawTitle(painter);
}

void ChatWidget::drawTitle(QPainter &painter)
{
    QPen pen(QColor("#888888"));
    painter.setFont(QFont("sans-serif", 10)); // 设置字体样式
    painter.setPen(pen);

    painter.drawText(5, 40, m_ClientIP);

    pen.setColor(Qt::black);
    painter.setFont(QFont("system-ui", 15)); // 设置字体样式
    painter.setPen(pen);
    painter.drawText(5, 20, m_ClientName);

    pen.setColor(Qt::black);
    painter.setPen(pen);
    painter.drawLine(0,50,740,50);
    painter.drawLine(0,500,740,500);

}

void ChatWidget::getFilePath()
{
    QStringList filePaths = QFileDialog::getOpenFileNames(
        this,                       // 父窗口
        tr("打开文件"),              // 对话框标题
        QDir::homePath(),           // 默认路径（如用户目录）
        tr("所有文件 (*)") // 文件过滤器
        );
    if (!filePaths.isEmpty()) {
        for (const QString &file : filePaths) {
            emit singal_SendFile(m_ClientIP,file);
        }
    }
}
